package com.core.website.service.impl;

import com.core.website.entity.DutyTemplate;
import com.core.website.entity.DutyTemplateDetail;
import com.core.website.mapper.DutyMapper;
import com.core.website.service.DutyService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class DutyServiceImpl implements DutyService {
    @Autowired
    private DutyMapper dutyMapper;
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int addTemplate(DutyTemplate dutyTemplate) {
        if("1".equals(dutyTemplate.getType())){
            dutyMapper.updateDefault();
        }
        dutyTemplate.setId(UUID.randomUUID().toString().toUpperCase().replace("-", ""));
        return dutyMapper.addTemplate(dutyTemplate);
    }

//    @Override
//    @Transactional(rollbackFor = Exception.class)
//    public int deleteTemplate(List<String> ids) {
//        dutyMapper.deleteDutyByTemplateIds(ids);
//        return dutyMapper.deleteTemplate(ids);
//    }

    @Override
    public List<DutyTemplate> queryTemplateAll() {
        return dutyMapper.queryTemplateAll();
    }

    @Override
    public DutyTemplate queryTemplateOne(String id) {
        return dutyMapper.queryTemplateOne(id);
    }

    @Override
    public int addTemplateDetail(DutyTemplateDetail dutyTemplateDetail) {
        dutyTemplateDetail.setId(UUID.randomUUID().toString().toUpperCase().replace("-", ""));
        return dutyMapper.addTemplateDetail(dutyTemplateDetail);
    }
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int delTemplateDetail(List<String> ids) {
        dutyMapper.deleteDutyByTemplateDetailIds(ids);
        return dutyMapper.deleteTemplateDetail(ids);
    }

    @Override
    public List<DutyTemplateDetail> queryDetailByTemplateId(String templateId) {
        return dutyMapper.queryDetailByTemplateId(templateId);
    }

    @Override
    public List<Map<String,Object>> queryDutyByDay(String day) {
        List<Map<String,Object>> list=dutyMapper.queryDutyByDay(day);
        if(null==list||list.size()==0){
            DutyTemplate template = dutyMapper.queryTemplateDefault();
            if(null!=template){
                List<DutyTemplateDetail> dutyTemplates = dutyMapper.queryDetailByTemplateId(template.getId());
                if(null!=dutyTemplates&&dutyTemplates.size()>0){
//                    dutyMapper.queryTemplateOne(dutyTemplates.get(0).getTemplateId())
                    List<Map<String,Object>> result=new ArrayList<>();
                    for(DutyTemplateDetail dutyTemplate:dutyTemplates){
                        Map<String,Object> map=new HashMap<>();
                        String id = dutyTemplate.getId();
                        map.put("id",id);
                        map.put("templateId",dutyTemplate.getTemplateId());
                        map.put("key",dutyTemplate.getName());
                        map.put("sort",dutyTemplate.getSort());
                        map.put("name","");
                        result.add(map);
                    }
                    return result;
                }
            }
        }else{
            Map<Object, List<Map<String, Object>>> groupByTemplateId = list.stream().collect(Collectors.groupingBy(x -> x.get("id")));
            String detailId = list.get(0).get("id").toString();
            DutyTemplateDetail dutyTemplateDetail = dutyMapper.queryDetailById(detailId);
            List<DutyTemplateDetail> dutyTemplates = dutyMapper.queryDetailByTemplateId(dutyTemplateDetail.getTemplateId());
            if(null!=dutyTemplates&&dutyTemplates.size()>0){
                List<Map<String,Object>> result=new ArrayList<>();
                for(DutyTemplateDetail dutyTemplate:dutyTemplates){
                    Map<String,Object> map=new HashMap<>();
                    String id = dutyTemplate.getId();
                    map.put("id",id);
                    map.put("templateId",dutyTemplate.getTemplateId());
                    map.put("key",dutyTemplate.getName());
                    map.put("sort",dutyTemplate.getSort());
                    map.put("name","");
                    List<Map<String, Object>> maps = groupByTemplateId.get(id);
                    if(null!=maps&&maps.size()>0){
                        map.put("name",maps.get(0).get("name"));
                        map.put("dutyUserName",maps.get(0).get("duty_user_name")); // 存一下是哪个用户排班的信息
                    }
                    result.add(map);
                }
                return result;
            }
        }

        return new ArrayList<>();
    }

    public DutyTemplate queryDutyTemplateByDay(String day) {
        List<Map<String, Object>> list = dutyMapper.queryDutyByDay(day);
        if (null == list || list.size() == 0) {
            DutyTemplate template = dutyMapper.queryTemplateDefault();
            return template;
        } else {
            Map<Object, List<Map<String, Object>>> groupByTemplateId = list.stream().collect(Collectors.groupingBy(x -> x.get("id")));
            String detailId = list.get(0).get("id").toString();
            DutyTemplateDetail dutyTemplateDetail = dutyMapper.queryDetailById(detailId);
            DutyTemplate dutyTemplate1 = dutyMapper.queryTemplateOne(dutyTemplateDetail.getTemplateId());
            return dutyTemplate1;

        }
    }
    @Override
    public DutyTemplate queryTemplateByDay(String day) {
        List<Map<String,Object>> list=dutyMapper.queryDutyByDay(day);
        if(null==list||list.size()==0){
            DutyTemplate template = dutyMapper.queryTemplateDefault();
            return template;
        }else{
            String detailId = list.get(0).get("id").toString();
            DutyTemplateDetail dutyTemplateDetail = dutyMapper.queryDetailById(detailId);
            DutyTemplate template = dutyMapper.queryTemplateOne(dutyTemplateDetail.getTemplateId());
            return template;
        }
    }

    @Override
    public int addDuty(List<Map<String,Object>> param,String day,String templateId) throws ParseException {
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
        Date parse = sdf.parse(day);
        List<DutyTemplateDetail> dutyTemplates = dutyMapper.queryDetailByTemplateId(templateId);
        Map<String, List<DutyTemplateDetail>> groupByTemplateId = dutyTemplates.stream().collect(Collectors.groupingBy(x -> x.getId()));
        for(Map<String,Object> map:param){
            if(null!=map.get("id")){
                List<DutyTemplateDetail> dutyTemplateDetail = groupByTemplateId.get(map.get("id"));
                if(null!=dutyTemplateDetail&&dutyTemplateDetail.size()>0){
                    String name =null==map.get("name")?"":map.get("name").toString();
                    dutyMapper.add(map.get("id").toString(),name,parse);
                }
            }
        }
        return 1;
    }
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateDuty(List<Map<String,Object>> param,String day,String templateId) throws ParseException {
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
        Date parse = sdf.parse(day);
        dutyMapper.deleteDutyByDay(parse);
        List<DutyTemplateDetail> dutyTemplates = dutyMapper.queryDetailByTemplateId(templateId);
        Map<String, List<DutyTemplateDetail>> groupByTemplateId = dutyTemplates.stream().collect(Collectors.groupingBy(x -> x.getId()));
        for(Map<String,Object> map:param){
            if(null!=map.get("id")){
                List<DutyTemplateDetail> dutyTemplateDetail = groupByTemplateId.get(map.get("id"));
                if(null!=dutyTemplateDetail&&dutyTemplateDetail.size()>0){
                    String name =null==map.get("name")?"":map.get("name").toString();
                    dutyMapper.add(map.get("id").toString(),name,parse);
                }
            }
        }
        return 1;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateDutyAndUserName(List<Map<String,Object>> param,String day,String templateId) throws ParseException {
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
        Date parse = sdf.parse(day);
        dutyMapper.deleteDutyByDay(parse);
        List<DutyTemplateDetail> dutyTemplates = dutyMapper.queryDetailByTemplateId(templateId);
        Map<String, List<DutyTemplateDetail>> groupByTemplateId = dutyTemplates.stream().collect(Collectors.groupingBy(x -> x.getId()));
        for(Map<String,Object> map:param){
            if(null!=map.get("id")){
                List<DutyTemplateDetail> dutyTemplateDetail = groupByTemplateId.get(map.get("id"));
                if(null!=dutyTemplateDetail&&dutyTemplateDetail.size()>0){
                    String name =null==map.get("name")?"":map.get("name").toString();
                    String dutyUserName =null==map.get("dutyUserName")?"":map.get("dutyUserName").toString();
                    dutyMapper.addDutyAndUserName(map.get("id").toString(),name,parse,dutyUserName);
                }
            }
        }
        return 1;
    }

    @Override
    public List<Map<String, Object>> queryFiveDuty() {
        Calendar calendar=Calendar.getInstance();
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
        List<Map<String,Object>> result=new ArrayList<>();
        for(int i=0;i<5;i++){
            Date time = calendar.getTime();
            String format = sdf.format(time);
            List<Map<String, Object>> maps = queryDutyByDay(format);
            DutyTemplate dutyTemplate = queryDutyTemplateByDay(format);
            Map<String,Object> map=new HashMap<>();
            map.put("day",format);
            map.put("data",maps);
            if(null!=dutyTemplate&&StringUtils.isNotEmpty(dutyTemplate.getId())){
                map.put("templateId",dutyTemplate.getId());
            }else{
                map.put("templateId","");
            }
            result.add(map);
            calendar.add(Calendar.DAY_OF_MONTH,1);
        }
        return result;
    }

    @Override
    public List<Map<String, Object>> queryMonthDuty(String month) {
        List<Map<String,Object>> result=new ArrayList<>();
        List<String> allMonthDays = getAllMonthDays(month);
        for(String day:allMonthDays) {
            Map<String,Object> map=new HashMap<>();
            map.put("day",day);
            map.put("isHas",false);
            List<Map<String, Object>> maps = dutyMapper.queryDutyByDay(day);
            if (null != maps && maps.size() > 0) {
                for(Map<String,Object> map1:maps){
                    if(null!=map1.get("name")&&StringUtils.isNotEmpty(map1.get("name").toString())){
                        map.put("isHas",true);
                    }
                }
            }
            result.add(map);
        }
        return result;
    }
    @Override
    public List<Map<String, Object>> queryMonthDutyAndUserName(String month,String userName) {
        List<Map<String,Object>> result=new ArrayList<>();
        List<String> allMonthDays = getAllMonthDays(month);
        for(String day:allMonthDays) {
            Map<String,Object> map=new HashMap<>();
            map.put("day",day);
            map.put("isHas",false);
            map.put("dutyUserName",userName);
            List<Map<String, Object>> maps = dutyMapper.queryMonthDutyAndUserName(map);
            if (null != maps && maps.size() > 0) {
                for(Map<String,Object> map1:maps){
                    if(null!=map1.get("name")&&StringUtils.isNotEmpty(map1.get("name").toString())){
                        map.put("isHas",true);
                    }
                }
            }
            result.add(map);
        }
        return result;
    }

    public static List<String> getAllMonthDays(String date) {
        int year = Integer.parseInt(date.substring(0, 4));
        int month = Integer.parseInt(date.substring(5));
        Calendar a = Calendar.getInstance();
        a.set(Calendar.YEAR, year);
        a.set(Calendar.MONTH, month - 1);
        a.set(Calendar.DATE, 1);
        a.roll(Calendar.DATE, -1);
        int days = a.get(Calendar.DATE);
        List<String> resultList = new ArrayList<String>();
        String monStr="";
        if(month<10){
            monStr="0"+month;
        }else{
            monStr=month+"";
        }
        for(int i=1;i<=days;i++) {
            String day = null;
            if(i<10) {
                day = String.valueOf(year)+"-"+monStr+"-0"+String.valueOf(i);
            }else {
                day = String.valueOf(year)+"-"+monStr+"-"+String.valueOf(i);
            }
            resultList.add(day);
        }
        return resultList;
    }
}
